package com.hjq.controller;

import com.hjq.pojo.Category;
import com.hjq.pojo.Result;
import com.hjq.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category) {
        log.info("新增文章分类，参数为: {}", category);
        categoryService.add(category);
        return Result.success();
    }

    @GetMapping
    public Result<List<Category>> list() {
        log.info("查询文章分类列表");
        List<Category> categories = categoryService.list();
        return Result.success(categories);
    }

    @GetMapping("/detail")
    public Result<Category> detail(Integer id) {
        log.info("查询文章分类详细信息，参数为：{}", id);
        Category category = categoryService.getById(id);
        return Result.success(category);
    }

    @PutMapping
    public Result update(@RequestBody @Validated(Category.Update.class) Category category) {
        log.info("更新文章分类，参数为：{}", category);
        categoryService.update(category);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(Integer id) {
        log.info("删除文章分类，参数为：{}", id);
        Category category = categoryService.getById(id);
        if (category == null) {
            return Result.error("文章分类不存在！");
        }
        categoryService.delete(id);
        return Result.success();
    }
}
